//
//  PersonLoginViewController.m
//  TestProject6
//
//  Created by JasonLee on 14/12/12.
//  Copyright (c) 2014年 JasonLee. All rights reserved.
//

#import "PersonPhoneLoginViewController.h"
#import "Common.h"
#import "ProtocolManager.h"
#import "LoginViewController.h"
#import "TransforController.h"

#define KEEP_PASSAWORD_LIST @"keepPassword.plst"
#define KEY_ACCOUNT @"key_account"
#define KEY_PASSWORD @"key_passord"
#define KEY_IFKEEPPASSWORD @"key_ifkeeppassord"
#define USER_INFO_LIST @"userinfo.text"
#define LOGINSTATUS @"loginStatus.plst"

@interface PersonPhoneLoginViewController (){
    CGRect rect;
    CGSize size;
    UITextField *_txtPhoneNumber;
    UITextField *_txtVerifyNumber;
    UIButton *btnGetVerifyNumber;
    NSString *verifyNumber;
    UIButton *btnConfirm;
    UILabel *title;
}


@end

@implementation PersonPhoneLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    rect = [UIScreen mainScreen].bounds;
    size = rect.size;
    [self initView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initView{
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"PhoneLoginView" owner:nil options:nil];
    self.view = [nibView objectAtIndex:0];
//    UIButton *btnGoBack = [UIButton buttonWithType:UIButtonTypeSystem];
//    btnGoBack.frame = CGRectMake(0, 25, 50, 30);
//    [btnGoBack setTitle:@"取消" forState:UIControlStateNormal];
//    [self.view addSubview:btnGoBack];
//    [btnGoBack addTarget:self action:@selector(goBackAction) forControlEvents:UIControlEventTouchUpInside];
    
    _txtPhoneNumber = (UITextField *)[self.view viewWithTag:30001];
//    _txtPhoneNumber = [[UITextField alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(btnGoBack.frame) + 20, size.width - 100, 30)];
//    _txtPhoneNumber.placeholder = @"请输入手机号";
//    _txtPhoneNumber.borderStyle = UITextBorderStyleRoundedRect;
//    [self.view addSubview:_txtPhoneNumber];
    
//    btnGetVerifyNumber = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    btnGetVerifyNumber.frame = CGRectMake(CGRectGetMaxX(_txtPhoneNumber.frame) + 5, CGRectGetMaxY(btnGoBack.frame) + 20, size.width - (CGRectGetMaxX(_txtPhoneNumber.frame) + 5), 30);
//    [btnGetVerifyNumber setTitle:@"获取验证码" forState:UIControlStateNormal];
    btnGetVerifyNumber = (UIButton *)[self.view viewWithTag:30003];
    [btnGetVerifyNumber addTarget:self action:@selector(getVerifyNumberAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btnGetVerifyNumber];
    
    _txtVerifyNumber = (UITextField *)[self.view viewWithTag:30002];
//    _txtVerifyNumber = [[UITextField alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(_txtPhoneNumber.frame) + 20, size.width - 10, 30)];
//    _txtVerifyNumber.placeholder = @"请输入短信中的验证码";
//    _txtVerifyNumber.borderStyle = UITextBorderStyleRoundedRect;
//    [self.view addSubview:_txtVerifyNumber];
    
//    UIButton *btnConfirm = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    btnConfirm.frame = CGRectMake(5, CGRectGetMaxY(_txtVerifyNumber.frame) + 20, size.width - 10, 30);
//    [btnConfirm setTitle:@"登录" forState:UIControlStateNormal];
    btnConfirm = (UIButton *)[self.view viewWithTag:30004];
    [btnConfirm addTarget:self action:@selector(doConfirmAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btnConfirm];
    UIImageView *img_temp = (UIImageView *)[self.view viewWithTag:900001];
    [img_temp setFrame:CGRectMake(0, 0, 320, 130)];
    
    title = (UILabel*)[self.view viewWithTag:120001];
    [self.view addSubview:img_temp];
    [self.view addSubview:title];
}

- (void)goBackAction{
    //[theTimer invalidate];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getVerifyNumberAction{
    if([_txtPhoneNumber.text isEqualToString:@""] || [_txtPhoneNumber.text length] != 11){
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"请输入正确的手机号码！" dismissTime:1.2];
        return;
    }else{
//        btnGetVerifyNumber.enabled = NO;
        
        [[ProtocolManager shareInstance] getVerifyCodeWithMobile:_txtPhoneNumber.text target:self selector:@selector(mobileValidationCallback:)];
        [self startTime];
    }
//    [[Common shareInstance]stopLoadingView];
}

- (void)mobileValidationCallback:(NSDictionary*)dic
{
    NSLog(@"mobileValidationCallback %@", dic)
    if (dic == nil) {
        return;
    }
    //verifyNumber = [Common valueForKey:P_CODE dic:dic];
    if([[Common valueForKey:@"respCode" dic:dic] isEqualToString:@"000"]){
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"短信发送成功" dismissTime:0.8];
        verifyNumber = [[NSString alloc]initWithFormat:@"%@",[Common valueForKey:P_CODE dic:dic]];
    }
    [[Common shareInstance]stopLoadingView];
    //NSLog(@"==>>PersonPhoneLoginViewController-->>doConfirmAction||verifyNumber:%@", verifyNumber);
}

+(void)loginWithTarget:(id)target selector:(SEL)sel mobile:(NSString *)mobile{
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    //app版本
    NSString* versionNum =[infoDict objectForKey:@"CFBundleVersion"];
    //手机型号
    NSString* phoneModel = [[UIDevice currentDevice] model];
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    //物理地址
    NSString* macAddr = [Common getMacAddr];
    [[ProtocolManager shareInstance]mobileLogin:mobile mobileModel:phoneModel loginCity:@"" appVersion:versionNum OSversion:phoneVersion mac:macAddr target:target selector:sel];
}

- (void)doConfirmAction{
    NSString *tempString = _txtVerifyNumber.text;
    //NSLog(@"==>>PersonPhoneLoginViewController-->>doConfirmAction||tempString:%@", tempString);
    if([tempString isEqualToString:verifyNumber]){
        NSLog(@"%s || verifyNumber's correct!", __FUNCTION__);
        //[[ProtocolManager shareInstance] mobileBinding:[ProtocolManager shareInstance].loginName mobile:_txtPhoneNumber.text target:self selector:@selector(getBindingActionCallBack:)];
        [[Common shareInstance]showLoadingViewWithMessage:nil];
        [PersonPhoneLoginViewController loginWithTarget:self selector:@selector(getLoginActionCallBack:) mobile:_txtPhoneNumber.text];
    }else{
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"请校验验证码是否正确！" dismissTime:1.2];
    }
//    [PersonPhoneLoginViewController loginWithTarget:self selector:@selector(getLoginActionCallBack:) mobile:_txtPhoneNumber.text];
}

- (void)getLoginActionCallBack:(NSDictionary *)dic{
    NSLog(@"%s || dic:%@", __FUNCTION__, dic)
    if (dic == nil) {
        return;
    }
    NSMutableDictionary *tempDic;
    //if([dic objectForKey:@"info"] == nil || [dic objectForKey:@"info"] == [NSNull null] || [[dic objectForKey:@"info"] length] < 1){
    if([dic[@"info"] objectForKey:@"Password"] == [NSNull null]){
        tempDic = [[NSMutableDictionary alloc]init];
    }else{
        tempDic = [dic objectForKey:@"info"];
    }
    if([dic objectForKey:@"loginname"] == [NSNull null]){
        [tempDic setValue:_txtPhoneNumber.text forKey:@"loginName"];
        [tempDic setValue:_txtPhoneNumber.text forKey:@"Mobile"];
        [tempDic setValue:@"手机用户" forKey:@"Username"];
    }else{
        [tempDic setValue:[dic objectForKey:@"loginname"] forKey:@"loginName"];
    }
    [tempDic setValue:[dic objectForKey:@"sessionId"] forKey:P_SID];
    //[tempDic setValue:[dic objectForKey:@"ID"] forKey:@"userId"];
    [tempDic setValue:@"0002" forKey:@"loginType"];
    [tempDic setValue:[dic objectForKey:@"respCode"] forKey:@"respCode"];
    NSLog(@"%s || tempDic:%@", __FUNCTION__, tempDic);
    [self getLoginCallBack2:tempDic];
    //[[NSUserDefaults standardUserDefaults] setObject:_txtPhoneNumber.text forKey:P_MOBILE];
    //[[Common shareInstance] showAlertViewWithTitle:nil text:@"绑定成功！" dismissTime:1.2];
    //[self.delegate changeMobilePhoneAfterUpdateSuccess:_txtPhoneNumber.text];
    [[Common shareInstance]stopLoadingView];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)getLoginCallBack2:(NSDictionary *)dic{
//    [[Common shareInstance] stopLoadingView];
    if(dic == nil)
    {
        NSLog(@"%s || dic is nil", __FUNCTION__);
        return;
    }else{
        if([dic objectForKey:@"Sex"] == nil || [dic objectForKey:@"Sex"] == NULL || [dic objectForKey:@"Sex"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Sex"];
        }
        if([dic objectForKey:@"Birthday"] == nil || [dic objectForKey:@"Birthday"] == NULL || [dic objectForKey:@"Birthday"] == [NSNull null]){
            [dic setValue:@"1980-01-01" forKey:@"Birthday"];
        }
        if([dic objectForKey:@"Industry_to"] == nil || [dic objectForKey:@"Industry_to"] == NULL || [dic objectForKey:@"Industry_to"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Industry_to"];
        }
        if([dic objectForKey:@"Email"] == nil || [dic objectForKey:@"Email"] == NULL || [dic objectForKey:@"Email"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Email"];
        }
        if([dic objectForKey:@"Address"] == nil || [dic objectForKey:@"Address"] == NULL || [dic objectForKey:@"Address"] == [NSNull null]){
            [dic setValue:@"" forKey:@"Address"];
        }
        if([[dic objectForKey:@"Birthday"] isEqualToString:@"0000-00-00"]){
            [dic setValue:@"1980-01-01" forKey:@"Birthday"];
        }
    }
    NSLog(@"%s || dic:%@",__FUNCTION__, dic);
    NSUserDefaults *accountInfo = [NSUserDefaults standardUserDefaults];
    //[accountInfo setObject:[dic objectForKey:P_USERID] forKey:P_USERID];
    [accountInfo setObject: [dic objectForKey:@"Mobile"] forKey:@"Mobile"];
    [accountInfo setObject: [dic objectForKey:@"Username"] forKey:@"Username"];
    [accountInfo setObject:[dic objectForKey:@"Sex"] forKey:@"Sex"];
    [accountInfo setObject:[dic objectForKey:@"Birthday"] forKey:@"Birthday"];
    [accountInfo setObject:[dic objectForKey:@"Industry_to"] forKey:@"Industry_to"];
    [accountInfo setObject:[dic objectForKey:@"Email"] forKey:@"Email"];
    [accountInfo setObject:[dic objectForKey:@"Address"] forKey:@"Address"];
    [accountInfo synchronize];
    
    NSString *respCode = [Common valueForKey:P_RESPCODE dic:dic];
    if([respCode isEqualToString:CODE_HANDLE_SUCCESS])
    {
        [ProtocolManager shareInstance].sid = [Common valueForKey:P_SID dic:dic];
        [ProtocolManager shareInstance].userId = [[dic objectForKey:@"userId"] integerValue];
        [ProtocolManager shareInstance].loginName = [dic objectForKey:@"Loginname"];
        [ProtocolManager shareInstance].mobile = [dic objectForKey:@"Mobile"];
        [ProtocolManager shareInstance].currCash = [dic objectForKey:@"currCash"];
        [ProtocolManager shareInstance].isLoginedByPhone = YES;
        [[TransforController sharedInstanceOfThirdViewController] changeStatusAfterLogin:1];
        NSMutableDictionary *savingDic = [NSMutableDictionary dictionary];
        NSString *readFilePath = [FileManager getFullDocumentPath:LOGINSTATUS];
        NSDictionary *readDic = [NSDictionary dictionaryWithContentsOfFile:readFilePath];
        //[savingDic setValue:[dic objectForKey:P_SID] forKey:P_SID];
        [savingDic setValue:[dic objectForKey:P_USERID] forKey:P_USERID];
        [savingDic setValue:[readDic objectForKey:@"loginName"] forKey:@"loginName"];
        [savingDic setValue:[readDic objectForKey:KEY_PASSWORD] forKey:KEY_PASSWORD];
        [savingDic setValue:[dic objectForKey:@"Username"] forKey:@"Username"];
        [savingDic setValue:[dic objectForKey:P_MOBILENUMBER] forKey:P_MOBILENUMBER];
        [savingDic setValue:[dic objectForKey:@"Sex"] forKey:@"Sex"];
        [savingDic setValue:[dic objectForKey:@"Birthday"] forKey:@"Birthday"];
        [savingDic setValue:[dic objectForKey:@"Email"] forKey:@"Email"];
        [savingDic setValue:[dic objectForKey:@"Address"] forKey:@"Address"];
        [savingDic setValue:[dic objectForKey:@"Industry_to"] forKey:@"Industry_to"];
        [savingDic setValue:@"0002" forKey:@"LoginStatus"];
        [savingDic writeToFile:[FileManager getFullDocumentPath:LOGINSTATUS]atomically:YES];
        //        NSString *filePath = [FileManager getFullDocumentPath:LOGINSTATUS];
        //        NSDictionary *tempDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
        
        //[dic writeToFile:[FileManager getFullDocumentPath:LOGINSTATUS]atomically:YES];
    }
}


-(void)startTime{
    __block int timeout=30; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [btnGetVerifyNumber setTitle:@"获取验证码" forState:UIControlStateNormal];
                btnGetVerifyNumber.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
//                NSLog(@"____%@",strTime);
                [btnGetVerifyNumber setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                btnGetVerifyNumber.userInteractionEnabled = NO;
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}
@end
